package com.muy.json.view.component;

import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.wm.ToolWindow;
import com.intellij.openapi.wm.ToolWindowManager;
import com.intellij.openapi.wm.WindowManager;
import com.intellij.ui.content.Content;
import com.intellij.ui.content.ContentFactory;
import com.intellij.ui.content.ContentManagerEvent;
import com.intellij.ui.content.ContentManagerListener;
import com.muy.json.view.panel.json.JsonPathEvaluateSnippetViewJava;
import org.jetbrains.annotations.NotNull;

/**
 * @Author jiyanghuang
 * @Date 2022/8/7 13:50
 */
public class MrJsonComponent implements ContentManagerListener {

    private static final Logger LOGGER = Logger.getInstance(MrJsonComponent.class);

    private Project project;

    /**
     * 当前窗口
     */
    private ToolWindow toolWindow;

    private JsonPathEvaluateSnippetViewJava sequenceTab;

    /**
     * 生成对象
     *
     * @param project
     */
    protected MrJsonComponent(Project project) {
        this.project = project;
    }

    /**
     * 类似于 spring 获取 bean 对象
     *
     * @param project
     * @return
     */
    public static MrJsonComponent getInstance(Project project) {
        return project.getService(MrJsonComponent.class);
    }



    /**
     * 初始化组件
     */
    public void initRestComponent(ToolWindow toolWindow) {
        this.toolWindow = toolWindow;
        // 添加内容变更监听器
        toolWindow.getContentManager().addContentManagerListener(this);

        Content content;
        ContentFactory contentFactory = ApplicationManager.getApplication().getService(ContentFactory.class);
        sequenceTab = new JsonPathEvaluateSnippetViewJava(project);
        content = contentFactory.createContent(sequenceTab, "", false);
        toolWindow.getContentManager().addContent(content);
        toolWindow.activate(new Thread(), true);
    }



    @Override
    public void selectionChanged(@NotNull ContentManagerEvent event) {

    }

    public void register(Class<?> clazz, Object impl) {

    }

    public String cacheObjectKey(String displayName, String tabId) {
        return displayName + "-" + tabId;
    }

    public ToolWindow getToolWindow() {
        return toolWindow;
    }

    public void setToolWindow(ToolWindow toolWindow) {
        this.toolWindow = toolWindow;
    }

    public void paseJson(String json) {
        if(null == toolWindow){
            toolWindow = ToolWindowManager.getInstance(project).getToolWindow("MrJson");
        }
        if (toolWindow.isActive()) {
            sequenceTab.setSource(json);
        } else {
            toolWindow.activate(() -> {
                sequenceTab.setSource(json);
            }, true);
        }
    }
}
